package kr.co.bettersoft.pushchat.fragment;


import java.util.List;

import com.google.android.gcm.GCMRegistrar;

import kr.co.bettersoft.pushchat.activity.GCMIntentService;
import kr.co.bettersoft.pushchat.activity.LoginActivity;
import kr.co.bettersoft.pushchat.activity.R;
import kr.co.bettersoft.pushchat.common.CommonConstant;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

/**
 * FragmentHome
 *  프래그먼트 홈
 *  TabActivity 를 Fragment 방식으로 대체하면서 TabActivity 기능을 구현한 FragmentActivity 이며
 *   채팅리스트, 다이어리리스트,멤버리스트,더보기 등을 기존 탭 메뉴가 아닌 fragment 로 추가시켜서 사용 
 * @author blue
 *
 */
public class FragmentHome extends FragmentActivity{
	static String TAG = "FragmentHome";

	public static Activity fragmentHome ;

	String COLOR_NOT_SELECTED = "#000000";			
	String COLOR_SELECTED = "#0000ff";			

	// 공용 프립스
	SharedPreferences sharedPrefCustom;		

	// 자동 로그인 및 하드웨어 홈버튼 동작 관련
	//	static String merchantId;			// 가맹점 아이디
	public String userId;
	public static Boolean autoLogin ;		

	// 로케일
	static String countryCode;
	static String languageCode;

	ImageButton memberListBtn;
	ImageButton chattingListBtn;
	ImageButton diaryListBtn;
	ImageButton settingsBtn;
	TextView  main_menu_1_member;
	TextView  main_menu_2_chat;
	TextView  main_menu_3_diary;
	TextView  main_menu_4_more;


	int nowMenuPostion = 0;	// 같은 화면 두번 호출방지
	Boolean isSame = false;

	public static int restCallCnt = 0; 

	// 뒤로가기 버튼으로 닫을때 2번만에 닫히도록
	static int app_end = 0;			

	int firstFragmentId;		// 뒤로가기 버튼에 대한 상호 작용을 위해 첫번째 fragment 의 아이디값을 저장.




	////////////////////////////////////// GCM 
	String SENDER_ID = CommonConstant.SENDER_ID;
	AsyncTask<Void, Void, Void> mRegisterTask;
	public static String REGISTRATION_ID = "";		// 등록아이디

	////////////////////////////////////////////////////////////////////////////////////////////////////

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature( Window.FEATURE_NO_TITLE );
		setContentView(R.layout.fragment_main);

		checkNetworkContinue();

		// 화면 안꺼지게
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		fragmentHome = FragmentHome.this;

		sharedPrefCustom = getSharedPreferences(CommonConstant.prefName,
				Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
		autoLogin = sharedPrefCustom.getBoolean("autoLoginChecked", false);
		// prefs
		userId = sharedPrefCustom.getString("userId", "");
		nextProcessing();

		memberListBtn = (ImageButton) findViewById(R.id.member_list_btn);
		chattingListBtn = (ImageButton) findViewById(R.id.chatting_list_btn);
		diaryListBtn = (ImageButton) findViewById(R.id.diary_list_btn);
		settingsBtn = (ImageButton) findViewById(R.id.settings_btn);

		memberListBtn.setOnClickListener(onBtnClickListener);
		chattingListBtn.setOnClickListener(onBtnClickListener);
		diaryListBtn.setOnClickListener(onBtnClickListener);
		settingsBtn.setOnClickListener(onBtnClickListener);

		main_menu_1_member = (TextView) findViewById(R.id.main_menu_1_member);
		main_menu_2_chat = (TextView) findViewById(R.id.main_menu_2_chat);
		main_menu_3_diary = (TextView) findViewById(R.id.main_menu_3_diary);
		main_menu_4_more = (TextView) findViewById(R.id.main_menu_4_more);

		showDetailFragment("MemberList");
	}



	/**
	 * nextProcessing
	 *  GCM 세팅하여 등록한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void nextProcessing(){
		////////////////////////////////////////////GCM 세팅        ///////////////////////////////////////////////////////////////		
		GCMRegistrar.checkDevice(this);					// 임시 중지  ->해제
		GCMRegistrar.checkManifest(this);				
		Log.i(TAG, "registerReceiver1 ");
		mRegisterTask = new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(Void... params) {	// 무조건 GCM 등록한다. 이전값이든 새값이든 등록하고 //등록 결과를 서버에 업뎃하는 부분은 GCM서비스에서 처리한다.
				GCMIntentService.userId = userId;
				GCMRegistrar.register(getThis(), SENDER_ID);	
				return null;
			}
			@Override
			protected void onPostExecute(Void result) {
				mRegisterTask = null;
			}
		};
		mRegisterTask.execute(null, null, null);
	}
	/**
	 * getThis
	 *  컨택스트 리턴한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public Context getThis(){
		return this;
	}

	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	private void showDetailFragment(String fragmentTag)
	{
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment newFragment = new MemberListFragment();

		if (fragmentTag.contains("MemberList")) {
			if(nowMenuPostion!=1){
				nowMenuPostion = 1;

				memberListBtn.setColorFilter(Color.parseColor(COLOR_SELECTED));
				chattingListBtn.setColorFilter(Color.parseColor(COLOR_NOT_SELECTED));
				diaryListBtn.setColorFilter(Color.parseColor(COLOR_NOT_SELECTED));
				settingsBtn.setColorFilter(Color.parseColor(COLOR_NOT_SELECTED));
				main_menu_1_member.setTextColor(Color.parseColor(COLOR_SELECTED));
				main_menu_2_chat.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
				main_menu_3_diary.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
				main_menu_4_more.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));

				//				registerWaitBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_5_over));
				//				waitUserListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_6));
				//				memberStoreReviewListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_7));
				//				settingsBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_8));
				newFragment = new MemberListFragment();		
				isSame = false;
			}else{
				isSame = true;
			}
		}else if(fragmentTag.contains("ChattingList")){
			if(nowMenuPostion!=2){
				nowMenuPostion = 2;
				memberListBtn.setColorFilter(Color.parseColor(COLOR_NOT_SELECTED));
				chattingListBtn.setColorFilter(Color.parseColor(COLOR_SELECTED));
				diaryListBtn.setColorFilter(Color.parseColor(COLOR_NOT_SELECTED));
				settingsBtn.setColorFilter(Color.parseColor(COLOR_NOT_SELECTED));
				main_menu_1_member.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
				main_menu_2_chat.setTextColor(Color.parseColor(COLOR_SELECTED));
				main_menu_3_diary.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
				main_menu_4_more.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
				//				registerWaitBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_5));
				//				waitUserListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_6_over));
				//				memberStoreReviewListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_7));
				//				settingsBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_8));
				newFragment = new ChattingListFragment();			
				isSame = false;
			}else{
				isSame = true;
			}


		}else if(fragmentTag.contains("DiaryList")){
			if(nowMenuPostion!=3){
				nowMenuPostion = 3;
				memberListBtn.setColorFilter(Color.parseColor(COLOR_NOT_SELECTED));
				chattingListBtn.setColorFilter(Color.parseColor(COLOR_NOT_SELECTED));
				diaryListBtn.setColorFilter(Color.parseColor(COLOR_SELECTED));
				settingsBtn.setColorFilter(Color.parseColor(COLOR_NOT_SELECTED));
				main_menu_1_member.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
				main_menu_2_chat.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
				main_menu_3_diary.setTextColor(Color.parseColor(COLOR_SELECTED));
				main_menu_4_more.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
				//				registerWaitBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_5));
				//				waitUserListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_6));
				//				memberStoreReviewListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_7_over));
				//				settingsBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_8));
				newFragment = new DiaryListFragment();			
				isSame = false;
			}else{
				isSame = true;
			}
		}else if(fragmentTag.contains("Settings")){
			if(nowMenuPostion!=4){
				nowMenuPostion = 4;
				memberListBtn.setColorFilter(Color.parseColor(COLOR_NOT_SELECTED));
				chattingListBtn.setColorFilter(Color.parseColor(COLOR_NOT_SELECTED));
				diaryListBtn.setColorFilter(Color.parseColor(COLOR_NOT_SELECTED));
				settingsBtn.setColorFilter(Color.parseColor(COLOR_SELECTED));
				main_menu_1_member.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
				main_menu_2_chat.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
				main_menu_3_diary.setTextColor(Color.parseColor(COLOR_NOT_SELECTED));
				main_menu_4_more.setTextColor(Color.parseColor(COLOR_SELECTED));
				//				registerWaitBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_5));
				//				waitUserListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_6));
				//				memberStoreReviewListBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_7));
				//				settingsBtn.setBackgroundDrawable((BitmapDrawable) this.getResources().getDrawable(R.drawable.sub1_8_over));
				newFragment = new SettingsFragment();			
				isSame = false;
			}else{
				isSame = true;
			}
		}

		if(!isSame){
			ft.replace(R.id.details, newFragment);								// fragment_main 의 detail 자리에 넣음
			ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			ft.commit();
			if(nowMenuPostion == 1){
				Log.d(TAG,"newFragment::"+newFragment.getId());
				firstFragmentId = newFragment.getId();
			}
		}
	}

	private OnClickListener onBtnClickListener = new OnClickListener()
	{
		@Override
		public void onClick(View v) {
			showDetailFragment(v.getTag().toString());
		}
	};


	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	public static Boolean restCallCntUp(){
		Boolean cntResult = false;
		restCallCnt = restCallCnt +1;
		Log.d(TAG,"restCallCnt:"+restCallCnt);
		if(restCallCnt==1){
			cntResult = true;
		}else{
			restCallCnt = restCallCnt -1;
			cntResult = false;
		}
		return cntResult;
	}
	public static Boolean restCallCntDown(){
		Boolean cntResult = false;
		restCallCnt = restCallCnt -1;
		Log.d(TAG,"restCallCnt:"+restCallCnt);
		if(restCallCnt==0){
			cntResult = true;
		}else{
			cntResult = false;
		}
		return cntResult;
	}
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////	

	// 통신 체크.
	public void checkNetworkContinue(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
					if(ni!=null){
						boolean isWifiAvail = ni.isAvailable();
						boolean isWifiConn = ni.isConnected();
						ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
						boolean isMobileAvail = ni.isAvailable();
						boolean isMobileConn = ni.isConnected();
						String status = "WiFi Avail = " + isWifiAvail + "// WiFi Conn = "
						+ isWifiConn + "// Mobile // Avail = " + isMobileAvail
						+ "// Conn = " + isMobileConn;
						//							Log.d(TAG,"status:"+status);
						Thread.sleep(5000);
						checkNetworkContinue();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}



	///////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	// 유틸	

	/**
	 * isForeGround
	 *  프로세스가 최상위로 실행중인지 검사한다
	 *
	 * @param
	 * @param
	 * @return rtn    @return true = 최상위
	 */
	public Boolean isForeGround(){
		ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE );
		List<RunningTaskInfo> list = am.getRunningTasks(1);
		ComponentName cn = list.get(0). topActivity;
		String name = cn.getPackageName();
		Boolean rtn = false;
		if(name.indexOf(getPackageName()) > -1){
			rtn = true;
		} else{
			rtn = false;
		}
		return rtn;
	}

	/*
	 *  닫기 버튼 2번 누르면 종료 됨.(non-Javadoc)
	 * @see android.app.Activity#onBackPressed()
	 */
	/**
	 * onBackPressed
	 *   닫기 버튼 2번 누르면 종료 한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	@Override
	public void onBackPressed() {
		Log.d(TAG, "FragmentHome finish");	

		//		// 대기 등록 프래그먼트 인지 확인.
		//		if(nowMenuPostion==1){
		//			Log.d(TAG,"register wait fragment");
		//			MemberListFragment registerWaitFragment = (MemberListFragment)getSupportFragmentManager().findFragmentById(registerWaitFragmentId);
		//			if(registerWaitFragment.checkFinishYn()){	
		//				Log.d(TAG,"mode : 1");
		//				finishAtTwo();
		//				// 대기 등록중인 화면. 
		//			}else{
		//				// 안해도 됨
		//				Log.d(TAG,"mode != 1. init screen");
		//			}
		//			// 일반 화면
		//		}else{
		//			Log.d(TAG,"other fragment");
		finishAtTwo();
		//		}
	}

	/*
	 * 3초 이내에 두번 연속 호출되면 어플을 종료함.
	 */
	public void finishAtTwo(){
		if(app_end == 1){
			Log.d(TAG,"kill all");
			finish();
		}else{
			app_end = 1;
			Toast.makeText(FragmentHome.this, R.string.noti_back_finish, Toast.LENGTH_SHORT).show();
			new Thread( 
					new Runnable(){
						public void run(){
							try {
								Thread.sleep(3000);
								app_end = 0;
							} catch (InterruptedException e) {e.printStackTrace();}
						}
					}
			).start();
		}
	}


	/**
	 * onResume
	 * 액티비티 리쥼시 바탕화면 갔다왔는지 확인해서 로그인창을 띄운다
	 *
	 * @param
	 * @param
	 * @return 
	 */
	@Override
	protected void onResume() {
		super.onResume();
		//		Log.d(TAG,"onResume");
		if(CommonConstant.comeBack){		// 바탕화면 갔다온 경우 - 로그인 액티비티 실행. 그냥죽을지/정상로그인할지/로그인하고죽을지
			Intent LoginIntent = new Intent(FragmentHome.this, LoginActivity.class);
			startActivity(LoginIntent);
		}
	}

	/**
	 * onPause
	 * 종료인지, 홈버튼으로 나간건지 확인하여 처리한다
	 *
	 * @param
	 * @param
	 * @return 
	 */
	@Override
	protected void onPause() {
		super.onPause();
		if(!isForeGround()){  
			if(!autoLogin){				// 자동 로그인 아닐 경우에만 로그인 창이 뜬다.
				CommonConstant.comeBack = true;				// 다시 돌아왔을때 알아볼수 있도록 함.
				CommonConstant.tempMyID = userId;				// 다시 돌아왔을때 알아볼수 있도록 함.
			}
		}
	}

	@Override
	public void onDestroy(){
		SharedPreferences.Editor appRunningYnPref = sharedPrefCustom.edit();
		appRunningYnPref.putBoolean("appRunningYn", false);		// 실행중 아님.
		appRunningYnPref.commit();
		super.onDestroy();
		System.exit(0);
	}
}